<?php

class WallController extends Zend_Controller_Action
{

    public function init() {
        parent::init();

        if (Zend_Auth::getInstance()->hasIdentity())
        {
            $user = Zend_Auth::getInstance()->getIdentity();

            $this->view->userProfile = $user->profile;
            $this->view->user = $user;
        }
        else
            $this->_redirect('/index');
    }

    public function indexAction() {

        $friendUser = User::findOneById($this->_getParam('idUser'));

        //chekeo que exista el friend
        if ($friendUser == null)
        {
            $this->_redirect('/home/index');
        }

        //checkeo que el muro seleccionado no sea el del usuario loggeado
        if ($friendUser->id == $this->view->user->id)
            $this->_redirect('/home/index');


        //checkeo si son amigos
        $checkFriendship = Friendship::checkFriendStatus($friendUser->id);

        if ($checkFriendship != "0")
            $this->_redirect('/wall/notfriend/idFriend/' . $friendUser->id);

        //Si son amigos, checkear si tiene un grupo

        if (!UMbook_Manager::getUserAdminStatus())
        {
            $friendshipForeignInstance = Friendship::findOneByRequestFriendship($friendUser->id);

            if ($friendshipForeignInstance->group->id != null)
            {
                //checkeo sus permisos
                $groupForeignInstance = $friendshipForeignInstance->group;

                //determino el id del wall del wantedFriend o friendUser y le paso ese id como $idObject
                $wallFriend = Wall::findOneByIdUser($friendUser->id);
                $idObject = $wallFriend->object->id;

                $groupPermisionForeign = GroupPermission::findOneByObjectAndGroup($idObject, $groupForeignInstance->id);

                if ($groupPermisionForeign->permission == GroupPermission::HIDE)
                    $this->_redirect('/wall/notpermission/idFriend/' . $friendUser->id);

                if ($groupPermisionForeign->permission == GroupPermission::READ)
                    $this->view->permission = $groupPermisionForeign->permission;
            }
        }

        $this->view->friendUser = User::findOneById($this->_getParam('idUser'));

        $wall = Wall::findOneByIdUser($this->_getParam('idUser'));

        $this->view->wall = $wall;

        $this->view->publications = Publication::findAllByEntity($wall->object->id, 'DESC');
    }

    public function notfriendAction() {
        $wantedFriend = $this->_getParam('idFriend');

        //chekeo que no se trate del usuario logeado
        $user = Zend_Auth::getInstance()->getIdentity();

        if ($user->id == $wantedFriend)
        {
            //si entra aca es porque el id que recibe es el del usuario logeado
            //esto evita que la vista sugiera autoagregar al usuario logeado
            $this->_redirect('/home/index');
        }



        $this->view->wantedFriend = User::findOneById($wantedFriend);
    }

    public function notpermissionAction() {
        $wantedFriend = $this->_getParam('idFriend');
        $this->view->wantedFriend = User::findOneById($wantedFriend);
    }

    public function newpublicationAction() {

        $user = Zend_Auth::getInstance()->getIdentity();

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $publicationMessage = $this->_getParam('publicationMessage');
        $id_objetct_type = $this->_getParam('id_objetct_type');

        $objectType = Object::findOneById($id_objetct_type);

        try
        {
            $conn = Doctrine_Manager::connection();
            $conn->beginTransaction();

            $object = new Object();
            $object->user = $user;
            $object->object_type = Object::PUBLICATION;
            $object->save();

            $publication = new Publication();
            $publication->message = $publicationMessage;
            $publication->publication_type = $objectType->object_type;
            $publication->id_object_type = $id_objetct_type;
            $publication->object = $object;
            $publication->save();

            $conn->commit();

            $this->_redirect($_SERVER['HTTP_REFERER']);
        } catch (Exception $e)
        {
            $conn->rollback();

            echo $e->getMessage();
        }
    }

    public function deletecommentAction() {
        $user = Zend_Auth::getInstance()->getIdentity();

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $publicationID = $this->_getParam('idPublication');

        //chekeo si existe el idUsuario que se quiere agregar como amigo
        self::checkPublishIsMine($publicationID);

        $publication = Publication::findOneById($publicationID);

        try
        {
            $conn = Doctrine_Manager::connection();
            $conn->beginTransaction();

            $publication->object->delete();
            $publication->delete();

            $conn->commit();

            //$this->_redirect($_SERVER['HTTP_REFERER']); 
        } catch (Exception $e)
        {
            $conn->rollback();

            echo $e->getMessage();
        }
    }

    public function deletepublicationAction() {

        $user = Zend_Auth::getInstance()->getIdentity();

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $publicationID = $this->_getParam('idPublication');

        //chekeo si existe el idUsuario que se quiere agregar como amigo
        self::checkPublishIsMine($publicationID);
        $publicationParent = Publication::findOneById($publicationID);
        $publications = Publication::findAllByEntity($publicationParent->id_object);

        try
        {
            $conn = Doctrine_Manager::connection();
            $conn->beginTransaction();

            foreach ($publications as $publication)
            {
                $publication->object->delete();
                $publication->delete();
            }

            $publicationParent->object->delete();
            $publicationParent->delete();

            $conn->commit();
            
            return;

            //$this->_redirect($_SERVER['HTTP_REFERER']); 
        } catch (Exception $e)
        {
            $conn->rollback();

            echo $e->getMessage();
        }
    }


    private function checkPublishIsMine($idPublish) {
        $publication = Publication::findOneById($idPublish);
        
        $user = Zend_Auth::getInstance()->getIdentity();

        if ($publication->object->user->id != $user->id || UMbook_Manager::getUserAdminStatus())
        {
            $this->_forward('index', 'home');
        }
    }

}
